package com.ruoyi.order.service.impl;

import com.ruoyi.common.minio.util.SnowFlakeIdWorker;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.order.domain.CartItem;
import com.ruoyi.order.domain.Unpay;
import com.ruoyi.order.domain.VerOrder;
import com.ruoyi.order.domain.VerOrderItem;
import com.ruoyi.order.domain.dto.VerCartAllDto;
import com.ruoyi.order.mapper.VerAddressMapper;
import com.ruoyi.order.mapper.VerCartMapper;
import com.ruoyi.order.mapper.VerOrderItemMapper;
import com.ruoyi.order.mapper.VerOrderMapper;
import com.ruoyi.order.service.IVerOrderItemService;
import com.ruoyi.order.service.IVerOrderService;
import com.ruoyi.product.domain.ProductImage;
import com.ruoyi.product.domain.ProductSku;
import com.ruoyi.product.mapper.ProductImageMapper;
import com.ruoyi.product.mapper.ProductSkuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-21
 */
@Service
public class VerOrderServiceImpl implements IVerOrderService {
    @Autowired
    private VerOrderMapper verOrderMapper;
    @Autowired
    private VerOrderItemMapper verOrderItemMapper;
    @Autowired
    private VerAddressMapper verAddressMapper;
    @Autowired
    private IVerOrderItemService verOrderItemService;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductImageMapper productImageMapper;

    private SnowFlakeIdWorker idWorker = new SnowFlakeIdWorker(1, 1);
    @Autowired
    private VerCartMapper verCartMapper;

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public VerOrder selectVerOrderByOrderId(Long orderId) {
        return verOrderMapper.selectVerOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     *
     * @param verOrder 订单
     * @return 订单
     */
    @Override
    public List<VerOrder> selectVerOrderList(VerOrder verOrder) {
        List<VerOrder> verOrders = verOrderMapper.selectVerOrderList(verOrder);

        // 为每个订单查询对应的订单项
        for (VerOrder order : verOrders) {
            VerOrderItem queryItem = new VerOrderItem();
            queryItem.setOrderId(order.getOrderId());
            List<VerOrderItem> orderItems = verOrderItemMapper.selectVerOrderItemList(queryItem);
            order.setOrderItems(orderItems);

            ProductSku productSku = new ProductSku();
            productSku.setId(orderItems.get(0).getItemSkuId());
            List<ProductSku> productSkus = productSkuMapper.selectProductSkuList(productSku);
            order.setProductSkus(productSkus);

            ProductImage productImage = new ProductImage();
            productImage.setSkuId(orderItems.get(0).getItemSkuId());
            List<ProductImage> productImages = productImageMapper.selectProductImageList(productImage);
            order.setProductImages(productImages);
        }

        // 清理返回数据中的指定字段
        // cleanOrderData(verOrders);

        return verOrders;
    }

    /**
     * 新增订单
     *
     * @param verOrder 订单
     * @return 结果
     */
    @Override
    public int insertVerOrder(VerOrder verOrder) {
        Long maxOrderId = verOrderMapper.selectMaxId();
        verOrder.setOrderId(maxOrderId == null ? 1 : maxOrderId + 1);
        verOrder.setCreateTime(DateUtils.getNowDate());
        return verOrderMapper.insertVerOrder(verOrder);
    }

    /**
     * 修改订单
     *
     * @param verOrder 订单
     * @return 结果
     */
    @Override
    public int updateVerOrder(VerOrder verOrder) {
        return verOrderMapper.updateVerOrder(verOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteVerOrderByOrderIds(Long[] orderIds) {
        return verOrderMapper.deleteVerOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteVerOrderByOrderId(Long orderId) {
        return verOrderMapper.deleteVerOrderByOrderId(orderId);
    }

    /**
     * 支付
     *
     * @param verOrder
     * @return
     */
    @Override
    public int pay(VerOrder verOrder) {
        return verOrderMapper.pay(verOrder);
    }

    /**
     * 创建订单和订单项
     *
     * @param unpay 订单信息
     * @return 创建的订单信息
     */
    @Override
    @Transactional
    public Unpay addOrderWithItems(Unpay unpay) {
        // 参数验证
        if (unpay == null) {
            throw new RuntimeException("订单信息不能为空");
        }
        if (unpay.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        if (unpay.getTotalAmount() == null || unpay.getTotalAmount().trim().isEmpty()) {
            throw new RuntimeException("订单总金额不能为空");
        }
        if (unpay.getPayAmount() == null || unpay.getPayAmount().trim().isEmpty()) {
            throw new RuntimeException("实付金额不能为空");
        }
        if (unpay.getCartItems() == null || unpay.getCartItems().isEmpty()) {
            throw new RuntimeException("订单项不能为空");
        }

        // 获取用户默认地址ID（如果addressId为null）
        Long addressId = unpay.getAddressId();
        if (addressId == null) {
            String defaultAddressId = verAddressMapper.getDefault(unpay.getUserId());
            if (defaultAddressId != null && !defaultAddressId.trim().isEmpty()) {
                addressId = Long.parseLong(defaultAddressId);
            }
        }

        // 设置默认值
        String freight = unpay.getFreight();
        if (freight == null || freight.trim().isEmpty()) {
            freight = "0";
        }

        Integer shipMethod = unpay.getShipMethod();
        if (shipMethod == null) {
            shipMethod = 0;
        }

        // 1. 创建订单
        VerOrder order = new VerOrder();
        order.setOrderId(idWorker.nextId()); // 生成订单ID
        order.setUserId(unpay.getUserId());
        order.setTotalAmount(unpay.getTotalAmount());
        order.setPayAmount(unpay.getPayAmount());
        order.setActivityId(unpay.getActivityId());
        order.setCouponId(unpay.getCouponId());
        order.setFreight(freight);
        order.setAddressId(addressId);
        order.setShipMethod(shipMethod);
        order.setStatus("0"); // 待付款状态
        order.setCreateTime(DateUtils.getNowDate());

        // 插入订单
        int orderResult = insertVerOrder(order);
        if (orderResult <= 0) {
            throw new RuntimeException("创建订单失败");
        }

        // 2. 创建订单项
        for (CartItem cartItem : unpay.getCartItems()) {
            if (cartItem.getSkuId() == null) {
                throw new RuntimeException("商品SKU ID不能为空");
            }
            if (cartItem.getQuantity() == null || cartItem.getQuantity() <= 0) {
                throw new RuntimeException("商品数量必须大于0");
            }
            if (cartItem.getUnitPrice() == null) {
                throw new RuntimeException("商品单价不能为空");
            }
            if (cartItem.getOriginalPrice() == null) {
                throw new RuntimeException("商品原价不能为空");
            }

            VerOrderItem orderItem = new VerOrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setActivityId(cartItem.getActivityId());
            orderItem.setCouponId(cartItem.getCouponId());
            orderItem.setItemSkuId(cartItem.getSkuId());
            orderItem.setProtection(cartItem.getProtection());
            orderItem.setQuantity(cartItem.getQuantity().longValue());
            orderItem.setUnitPrice(cartItem.getUnitPrice());
            orderItem.setOriginalPrice(cartItem.getOriginalPrice());
            orderItem.setTotalPrice(cartItem.getUnitPrice().multiply(new BigDecimal(cartItem.getQuantity())));
            orderItem.setCreateTime(DateUtils.getNowDate());

            int itemResult = verOrderItemService.insertVerOrderItem(orderItem);
            if (itemResult <= 0) {
                throw new RuntimeException("创建订单项失败");
            }

            // 将购物车项标记为已删除
            Long cartItemId = cartItem.getCartItemId();
            if (cartItemId != null) {
                verCartMapper.logicalDelete(cartItemId);
            }
        }

        // 设置返回的订单ID
        unpay.setOrderId(order.getOrderId());

        return unpay;
    }

    /**
     * 获取商品原价
     *
     * @param id
     */
    @Override
    public Long getOriginalPrice(Long id) {
        return null;
    }

    /**
     * 根据用户ID获取订单和订单项列表
     *
     * @param userId
     */
    @Override
    public List<VerCartAllDto> selectVerOrderListByUserId(Long userId) {
        return null;
    }
}
